// miniprogram/pages/my/index.js
const app = getApp()
const regeneratorRuntime = require('../../libs/runtime')
Page({
    data: {
        userImg: "/images/icon/user-unlogin.png",
        userName: "一键授权登陆",
        logged: false,
        adminGrid: [{
                text: "我的订单",
                icon: "publishgoods_fill",
                url: "/pages/my/myOrderList"
            }, {
                text: "新增房间",
                icon: "activity",
                url: "/pages/admin/addRoom"
            },
            {
                text: "房间管理",
                icon: "activity",
                url: "/pages/admin/roomManager"
            }, {
                text: "修改联系方式",
                icon: "group",
                url: "/pages/admin/editAboutUs"
            }, {
                text: "相册编辑",
                icon: "picture",
                url: "/pages/admin/editImage"
            }
        ],
        grid: [{
            text: "我的订单",
            icon: "publishgoods_fill",
            url: "/pages/my/myOrderList"
        }],
        isShowItem: false
    },
    onLoad: function(options) {
        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            this.setData({
                                userImg: res.userInfo.avatarUrl,
                                userName: 'Hello,' + res.userInfo.nickName,
                                isShowItem: true
                            })
                            app.globalData.userInfo = res.userInfo
                        }
                    })
                }
            }
        })
    },
    async onGetUserInfo(e) {
        if (!this.logged && e.detail.userInfo) {
            this.setData({
                logged: true,
                userImg: e.detail.userInfo.avatarUrl,
                userName: 'Hello,' + e.detail.userInfo.nickName
            })
            app.globalData.userInfo = e.detail.userInfo
            wx.showLoading({
                title: '',
            })
            const {
                result
            } = await wx.cloud.callFunction({
                name: 'login',
            })
            let that = this
            if (result.isAdmin) {
                this.setData({
                    grid: that.data.adminGrid,
                    isShowItem: true
                })
            }
            wx.hideLoading()
        }
    },
    toUrl(e) {
        let url = e.currentTarget.dataset.url
        if (!url) {
            wx.showToast({
                title: '暂未开放',
                icon: "none"
            })
        }
        wx.navigateTo({
            url: url,
        })
    }
})